<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2022-01-20
 * Time: 14:44
 */

namespace app\common\item;

use app\common\exception\ServiceException;
use app\common\util\FFMpegUtil;

class UploadLoader extends BaseItemLoader
{

    const PLATFORM_LOCAL = 1;

    const PLATFORM_COS = 2;

    const PLATFORM_OSS = 3;

    const UPLOAD_IMAGE = 1;

    const UPLOAD_VIDEO = 2;

    const UPLOAD_DOC = 3;

    const UPLOAD_OTHER = 4; //其他类型的文件


    public static function getFileTypeByExt($ext)
    {
        $ext = strtolower($ext);
        $default = self::UPLOAD_IMAGE;
        $arr = [
            self::UPLOAD_IMAGE => ["ico", "icon", "jpg", "jpeg", "png", "gif"],
            self::UPLOAD_VIDEO => ["mp4"],
            self::UPLOAD_DOC => ["doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "rar", "zip"],
            self::UPLOAD_OTHER => ["mp3"],
        ];
        foreach ($arr as $key => $row) {
            if (in_array($ext, $row)) {
                $default = $key;
            }
        }
        return $default;
    }


    public function getFieldInfo($key, $move_path, $params = [])
    {
        $item = [];
        $file = request()->file($key); //获取对象
        if (empty($file)) {
            throw  new ServiceException("文件不存在");
        }
        $origin_info = $file->getInfo();
        $info = $file->validate(['size' => get_sysconfig("upload_size"), 'ext' => get_sysconfig("upload_ext")])->rule('md5')->move($move_path);
        if (!$info) {
            throw new ServiceException($file->getError());
        }
        $item['type'] = isset($params['type']) ? $params['type'] : self::getFileTypeByExt($info->getExtension());
        $item['mime'] = $origin_info['type'];
        $item['title'] = substr($origin_info['name'], 0, strrpos($origin_info['name'], "."));
        $item['ext'] = $info->getExtension();
        $item['hash'] = $info->md5();
        $item['size'] = $origin_info['size'];
        $item['path'] = realpath($move_path . "/" . $info->getSaveName());
        if ($item['type'] == self::UPLOAD_VIDEO) {
            $ffmpeg_util = FFMpegUtil::Instance();
            $video_info = $ffmpeg_util->getInfo($item['path']);
            $item['play_time'] = $video_info['duration'];
        }
        $this->item = $item;
        return $this->item;
    }


}